﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Reflection;
using System.Web.Script.Serialization;

namespace NLBS.Web.HttpHandlers
{
    public class AjaxHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Request.Form.Keys
            MethodInfo methodInfo = this.GetType().GetMethod(context.Request.PathInfo.Substring(1));
            ParameterInfo[] infos = methodInfo.GetParameters();
            object[] paraObject = new object[infos.Length];

            for (int i = 0; i < infos.Length; i++)
            {
                if (context.Request.Form.Count > 0)
                {
                    paraObject[i] = ProcessParameterValue(context.Request.Form[infos[i].Name], infos[i]);
                }
                if (context.Request.QueryString.Count > 0)
                {
                    paraObject[i] = ProcessParameterValue(context.Request.QueryString[infos[i].Name], infos[i]);
                }
            }
            try
            {
                context.Response.Write(methodInfo.Invoke(this, paraObject));
            }
            catch (Exception e)
            {
                context.Response.Clear();
                context.Response.ContentType = "text/xml";
                context.Response.Write("<CallbackError><![CDATA[");
                context.Response.Write(e.InnerException.Message);
                context.Response.Write("]]></CallbackError>");
                context.Response.End();
               
            }
        }

       

        public string Serialize(object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        private object ProcessParameterValue(object inputValue, ParameterInfo parameterInfo)
        {
            if (inputValue == null)
            {
                return null;
            }
            Type c = inputValue.GetType();
            Type parameterType = parameterInfo.ParameterType;
            if (parameterType.IsAssignableFrom(c))
            {
                return inputValue;
            }
            if (c == typeof(string))
            {
                TypeConverter converter = TypeDescriptor.GetConverter(parameterType);
                if ((converter != null) && converter.CanConvertFrom(typeof(string)))
                {
                    return converter.ConvertFromInvariantString((string)inputValue);
                }
            }
            return Convert.ChangeType(inputValue, parameterType, CultureInfo.InvariantCulture);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
